package com.kelp.codetoolkit.utils

import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Computable
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiManager

/**
 * @author: liuyuebai
 * @date: 2024/8/3 13:38
 * @description:
 */
object IdeaFileHandleUtil {

    fun createDirectory(project: Project,parent:VirtualFile,directoryName:String):VirtualFile?{
        return WriteCommandAction.runWriteCommandAction(project, Computable {
          return@Computable VfsUtil.createDirectoryIfMissing(parent, directoryName)
        })
    }

    fun createDirectory(project: Project,directoryName:String):VirtualFile?{
        return WriteCommandAction.runWriteCommandAction(project, Computable {
            return@Computable VfsUtil.createDirectories(directoryName)
        })
    }

    fun createFile(project: Project, parent: VirtualFile, fileName: String): VirtualFile? {
        return WriteCommandAction.runWriteCommandAction(project, Computable {
            val psiManager = PsiManager.getInstance(project)
            val findDirectory = psiManager.findDirectory(parent)
            if (findDirectory != null) {
                val psiFile = findDirectory.createFile(fileName)
                return@Computable psiFile.virtualFile
            }
            return@Computable parent.createChildData(Any(),fileName)
        })
    }

    fun coverFile(project:Project,file:VirtualFile,content:String): Document? {
         val fileDocumentManager = FileDocumentManager.getInstance()

         val document = fileDocumentManager.getDocument(file)
         if (null ==document) {
             WriteCommandAction.runWriteCommandAction(project){
                 file.setBinaryContent(content.toByteArray())
             }
             return fileDocumentManager.getDocument(file)
         }
        WriteCommandAction.runWriteCommandAction(project) { document.setText(content) }
        val psiDocumentManager =  PsiDocumentManager.getInstance(project);
        psiDocumentManager.commitDocument(document)
        return document
    }

}